package com.mujin.keji.collectionsystem.module.tripplan.views;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.route.BikingRouteResult;
import com.baidu.mapapi.search.route.DrivingRouteResult;
import com.baidu.mapapi.search.route.IndoorRouteResult;
import com.baidu.mapapi.search.route.MassTransitRouteLine;
import com.baidu.mapapi.search.route.MassTransitRoutePlanOption;
import com.baidu.mapapi.search.route.MassTransitRouteResult;
import com.baidu.mapapi.search.route.OnGetRoutePlanResultListener;
import com.baidu.mapapi.search.route.PlanNode;
import com.baidu.mapapi.search.route.RoutePlanSearch;
import com.baidu.mapapi.search.route.TransitRouteResult;
import com.baidu.mapapi.search.route.WalkingRouteResult;
import com.mujin.keji.collectionsystem.CcsApplication;
import com.mujin.keji.collectionsystem.R;
import com.mujin.keji.collectionsystem.base.BaseActivity;
import com.mujin.keji.collectionsystem.listeners.CustomItemClickListener;
import com.mujin.keji.collectionsystem.module.main.views.MainActivity;
import com.mujin.keji.collectionsystem.module.tripplan.adapter.CommonBusAdapter;
import com.mujin.keji.collectionsystem.module.tripplan.dto.MassTransitRouteLineDto;
import com.mujin.keji.collectionsystem.module.tripplan.dto.QueryPlanDetailDto;
import com.mujin.keji.collectionsystem.module.tripplan.vo.LatLonVo;
import com.mujin.keji.collectionsystem.utils.EmptyUtils;
import com.mujin.keji.collectionsystem.utils.RxTimerUtil;
import com.mujin.keji.collectionsystem.utils.ToastUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 公交路线规划界面
 *
 * @author weishixiong
 * @Time 2018-04-10
 */
public class BusListPlanActivity extends BaseActivity implements CustomItemClickListener {
    private RoutePlanSearch mSearch;
    private OnGetRoutePlanResultListener routeListener;
    private PlanNode startPlanNode;//起点
    private PlanNode stopPlanNode;//终点
    private RecyclerView recyclerview;
    private LinearLayoutManager linearLayoutManager;
    List<MassTransitRouteLine> massTransitRouteLineList;
    private CommonBusAdapter commonBusAdapter;
    private LatLonVo latLonVo;
    private List<Integer> durationList;
    private List<Integer> distanceList;
    private List<MassTransitRouteLineDto> massTransitRouteLineDtoList;
    /**
     * 需要绘制路线的公交行程列表
     */
    private List<MassTransitRouteLine> routeLines;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        CcsApplication.addActivity(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        CcsApplication.removeActivity(this);
        if (EmptyUtils.isNotEmpty(mSearch)) {
            mSearch.destroy();
        }
    }

    public void Event(LatLonVo vo) {
        //121.419871,
//        vo.setCurrentLon(121.419871);
//        vo.setCurrentLat(31.212342);
        if (!EmptyUtils.isNotEmpty(vo)) {
            ToastUtils.showToast("规划公交路线失败，请稍后再试");
            return;
        }
        ToastUtils.showToast("正在规划公交路线，请稍等");
        getLoadingDialog().showDialog();
        this.latLonVo = vo;
        startPlanNode = PlanNode.withLocation(new LatLng(vo.getCurrentLat(), vo.getCurrentLon()));
        stopPlanNode = PlanNode.withLocation(new LatLng(vo.getTargetLat(), vo.getTargetLon()));
        initBusPlanData();
    }

    /**
     * 初始化公交路线规划的一些数据
     */
    private void initBusPlanData() {
        mSearch = RoutePlanSearch.newInstance();
        routeListener = new OnGetRoutePlanResultListener() {
            @Override
            public void onGetWalkingRouteResult(WalkingRouteResult walkingRouteResult) {
            }

            @Override
            public void onGetTransitRouteResult(TransitRouteResult result) {
            }

            @Override
            public void onGetMassTransitRouteResult(MassTransitRouteResult result) {
                //获取跨城综合公共交通线路规划结果
                //路线数量，每一个item就是一条路线
                massTransitRouteLineList = result.getRouteLines();
                if (EmptyUtils.isNotEmpty(massTransitRouteLineList)) {
                    initListView();
                    routeLines = result.getRouteLines();
                }
            }

            @Override
            public void onGetDrivingRouteResult(DrivingRouteResult drivingRouteResult) {
            }

            @Override
            public void onGetIndoorRouteResult(IndoorRouteResult indoorRouteResult) {
            }

            @Override
            public void onGetBikingRouteResult(BikingRouteResult bikingRouteResult) {
            }
        };
        mSearch.setOnGetRoutePlanResultListener(routeListener);
        //发起规划检索
        mSearch.masstransitSearch(new MassTransitRoutePlanOption().from(startPlanNode).to(stopPlanNode));
        RxTimerUtil.timer(5000, new RxTimerUtil.IRxNext() {
            @Override
            public void doNext() {
                if(!EmptyUtils.isNotEmpty(routeLines)){
                    getLoadingDialog().dismiss();
                    ToastUtils.showToast("当前位置无法规划公交路线，请换个地点再试");
                }
                RxTimerUtil.cancel();
            }
        });

    }

    /**
     * 初始化列表视图
     */
    private void initListView() {
        try {
            durationList = new ArrayList<>();
            distanceList = new ArrayList<>();
            massTransitRouteLineDtoList = new ArrayList<>();
            linearLayoutManager = new LinearLayoutManager(this);
            //遍历每一条路线
            for (int i = 0; i < massTransitRouteLineList.size(); i++) {
                int distance = 0;
                MassTransitRouteLine massTransitRouteLine = massTransitRouteLineList.get(i);
                durationList.add(massTransitRouteLine.getDuration() / 60);
                //Logger.d(TAG, "aaaa路线---" + i + "时长: " + DateUtil.minForDay(massTransitRouteLine.getDuration() / 60));
                //遍历每条路线的步骤
                for (int j = 0; j < massTransitRouteLine.getNewSteps().size(); j++) {
                    //步骤
                    List<MassTransitRouteLine.TransitStep> transitStepList = massTransitRouteLine.getNewSteps().get(j);
                    for (int k = 0; k < transitStepList.size(); k++) {
                      //  Logger.d(TAG, "aaaa路线---" + i + ":" + j + ":" + k + ":" + DateUtil.minForDay(transitStepList.get(k).getDuration() / 60));
                        String instructions = transitStepList.get(k).getInstructions();
                        //
                        if (instructions.contains("步行") && instructions.contains("米")) {
                            //提取文字中的数字
                            String regEx = "[^0-9]";
                            Pattern p = Pattern.compile(regEx);
                            Matcher m = p.matcher(instructions);
                            distance += +Integer.parseInt(m.replaceAll("").trim());
                        }
                       // Logger.d(TAG, "aaaa路线---" + i + ":" + j + ":" + k + ":" + transitStepList.get(k).getInstructions());
                        if (transitStepList.get(k) != null && transitStepList.get(k).getBusInfo() != null) {
                            transitStepList.get(k).getTrafficConditions();
                            //Logger.d(TAG, "aaaa交通名称---" + i + ":" + j + ":" + k + ":" + transitStepList.get(k).getBusInfo().getName() + "交通类型：" + transitStepList.get(k).getBusInfo().getType());
                        }
                    }
                }
                distanceList.add(distance);
            }
            int indexDuration = durationList.indexOf(Collections.min(durationList));
            int indexDistance = distanceList.indexOf(Collections.min(distanceList));
            for (int i = 0; i < massTransitRouteLineList.size(); i++) {
                if (i == indexDuration) {
                    massTransitRouteLineDtoList.add(new MassTransitRouteLineDto(true, false, latLonVo, massTransitRouteLineList.get(i)));
                } else if (i == indexDistance) {
                    massTransitRouteLineDtoList.add(new MassTransitRouteLineDto(false, true, latLonVo, massTransitRouteLineList.get(i)));
                } else {
                    massTransitRouteLineDtoList.add(new MassTransitRouteLineDto(false, false, latLonVo, massTransitRouteLineList.get(i)));
                }

            }
            recyclerview.setLayoutManager(linearLayoutManager);
            commonBusAdapter = new CommonBusAdapter(this, massTransitRouteLineDtoList, this);
            recyclerview.setAdapter(commonBusAdapter);
            getLoadingDialog().dismiss();

        } catch (Exception e) {
          //  Logger.d(TAG, "initListView: " + e);
        }


    }

    @Override
    protected void createViewModel() {

    }

    @Override
    public int intiLayout() {
        return R.layout.activity_buslistplan;
    }

    @Override
    public void initView() {
        setrightImage(R.drawable.image_to_main, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CcsApplication.clearAllActivitys();
                startActivity(new Intent(BusListPlanActivity.this, MainActivity.class));
            }
        });
        recyclerview = (RecyclerView) findViewById(R.id.recyclerview);
        setCenterTitle("行程规划", "#FFFFFF");
        setleftImage(R.drawable.image_arrow_left_white, true, null);
    }

    LatLonVo vo;


    @Override
    public void initData() {
        vo = (LatLonVo) getIntent().getSerializableExtra("vo");
        queryPlanDetailDto = (QueryPlanDetailDto) getIntent().getSerializableExtra("queryPlanDetailDto");
        Event(vo);

    }

    @Override
    public void initListener() {

    }
    private QueryPlanDetailDto queryPlanDetailDto;
    @Override
    public void onItemClick(View view, int position) {
        Intent intent = new Intent(this, BusPlanDetailActivity.class);
        startActivity(intent);
        massTransitRouteLineDtoList.get(position).setTransitRouteLine(routeLines.get(position));
        massTransitRouteLineDtoList.get(position).setQueryPlanDetailDto(queryPlanDetailDto);
        EventBus.getDefault().postSticky(massTransitRouteLineDtoList.get(position));

    }
}
